<template>
  <div class="app-container">
    <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery">
      <el-form-item slot="button">
        <el-button v-hasPermi="['system:account:add']" type="primary" @click="handleAdd">添加账号</el-button>
      </el-form-item>
    </YxhyTableQuery>

    <YxhyTableData :columns="columns" :data="tableList" :loading="loading">
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <div class="table-action-panel">
              <el-button v-hasPermi="['system:account:edit']" type="success" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button v-hasPermi="['system:account:role']" type="primary" size="mini" @click="handleBindRole(scope.row)">角色</el-button>
              <el-button v-hasPermi="['system:account:delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="状态" prop="status">
          <div class="flex ai-center">
            <el-switch v-model="form.status" />
            <p class="ml-10">{{ form.status ? '正常' : '封禁' }}</p>
          </div>
        </el-form-item>
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="form.account" maxlength="15" placeholder="请输入账号" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" maxlength="20" show-password placeholder="请输入密码" @change="passwordOnChange" />
        </el-form-item>
        <el-form-item label="版权">
          <el-checkbox v-model="isCopyright" @change="onChangeIsCopyright">版权角色</el-checkbox>
        </el-form-item>
        <template v-if="isCopyright">
          <el-form-item label="版权" prop="copyright_id" required>
            <YxhySelectRemote
              :value.sync="form.copyright_id"
              :request-fn="queryListCopyright"
              :request-key="`title_search`"
              :request-other="{
                list_search: 2
              }"
              :response-id="`copyright_id`"
              :response-name="`title`"
              :placeholder="`请输入版权名称`"
            />
          </el-form-item>
        </template>
        <el-form-item label="昵称" prop="chinese_name">
          <el-input v-model="form.chinese_name" placeholder="请输入昵称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 绑定角色对话框 -->
    <el-dialog :title="`绑定角色`" :visible.sync="bindRoleShow" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" label-width="80px">
        <el-form-item label="角色">
          <el-tree
            ref="menu"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindRoleCancel">取 消</el-button>
        <el-button type="primary" @click="submitBindRole">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { columnsStatic } from './Ds.js'
import { queryUserList, addUser, STATUS, updateUser, deleteUser } from '@/api/system/account'
import { roles, rolesJustName } from '@/rolesStaticData'
import { queryListCopyright } from '@/api/miniProgram/copyright'
import { bindRoleUser, listRole } from '@/api/system/role'

const staticPassword = '******'
export default {
  name: 'ClassifyList',
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      loading: false,
      // 查询参数
      queryParams: {
        role_search: undefined,
        name_search: undefined
      },
      // 查询表单
      queryColumns: [{
        label: '',
        placeholder: '请输入角色标识',
        type: 'input',
        param: 'role_search'
      }, {
        label: '',
        placeholder: '请输入昵称',
        type: 'input',
        param: 'name_search'
      }],
      // 表格列
      columns: columnsStatic,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      defaultProps: {
        children: 'children',
        label: 'display_name'
      },
      // 角色组
      bindForm: {
        u_id: undefined,
        roleIds: []
      },
      // 表单参数
      form: {
        account: undefined,
        password: undefined,
        status: true,
        role: undefined, // 角色标识，旧版
        chinese_name: undefined,
        copyright_id: undefined
      },
      // 表单校验
      rules: {
        account: [
          { required: true, message: '请输入登录账号', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: ['blur', 'change'] }
        ],
        copyright_id: {
          validator: (rule, value, callback) => {
            if (this.isCopyright && !value) callback(new Error('请选择版权'))
            else callback()
          },
          trigger: ['blur', 'change']
        },
        chinese_name: [
          { required: true, message: '请输入昵称', trigger: ['blur', 'change'] }
        ]
      },
      menuOptions: [],
      queryListCopyright,

      isPasswordChanged: false, // 修改时，登录密码修改过
      isCopyright: false, // 是否版权角色
      bindRoleShow: false
    }
  },
  computed: {
    isEdit() {
      return ![undefined, ''].includes(this.form.id)
    }
  },
  created() {
    this.init()

    this.setMenuOptions()
  },
  methods: {
    async init() {
      this.loading = true
      const res = await queryUserList({
        ...this.queryPage,
        ...this.queryParams
      })
      res.data.forEach(e => {
        e.status_text = STATUS[e.status]
        e.role_names_text = e.role_names.toString()
      })
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        account: undefined,
        password: undefined,
        status: true,
        role: undefined, // 角色标识
        chinese_name: undefined,
        copyright_id: undefined
      }
      this.resetForm('formRef')
    },

    bindRoleCancel() {
      this.bindRoleShow = false
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },

    /** 设置角色数据源 */
    setMenuOptions() {
      listRole().then(data => {
        this.menuOptions = data
      })
    },

    passwordOnChange() {
      if (this.isEdit && this.isPasswordChanged === false) {
        // 直接清空密码
        this.isPasswordChanged = true
        this.form.password = undefined
        this.$modal.msgWarning('为安全考虑，请再次输入登录密码')
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加账号'
    },
    onChangeIsCopyright(event) {
      if (event === false) this.form.copyright_id = 0
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const { id, status, username, role_ids, copyright_id } = row

      this.reset()
      this.isPasswordChanged = false
      this.isCopyright = !['', undefined, null, 0].includes(copyright_id)
      this.form = {
        ...row,
        action_id: id,
        account: username,
        password: staticPassword,
        status: status == 1
      }
      this.open = true
      this.title = '修改账号'
    },
    handleBindRole(row) {
      const { role_ids } = row
      this.reset()
      this.form = row
      this.bindRoleShow = true

      if (role_ids.length === 0) {
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys([])
        })
      } else {
        this.$nextTick(() => {
          role_ids.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(v, true, false)
            })
          })
        })
      }
    },
    /** 绑定角色 */
    async submitBindRole() {
      // 绑定角色
      let r_id = this.getMenuAllCheckedKeys()
      r_id = r_id.length === 0 ? [0] : r_id
      this.menuOptions.filter(menu => r_id.includes(menu.id)).map(menu => menu.name).join(',')
      // 绑定角色
      await bindRoleUser({
        u_id: this.form.id,
        r_id
      })
      this.bindRoleShow = false
      this.init()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.form.status = this.form.status ? 1 : 2
          if (this.form.password === staticPassword) {
            // 未修改密码，不传递密码参数
            this.form.password = undefined
          }

          this.form.role = this.isCopyright ? 'copyright' : 'oldParamStatic'

          if (this.isEdit) {
            updateUser(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.init()
            })
          } else {
            addUser(this.form).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.open = false
              this.init()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { id } = row
      this.$modal
        .confirm('是否确认删除吗？')
        .then(function() {
          return deleteUser({
            action_id: id
          })
        })
        .then(() => {
          this.init()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.item-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20px;
  .item-panel {
    width: 32%;
    background-color: #f8f8f8;
    padding: 10px;
    margin-bottom: 20px;
  }
}
.item-box:after{
  content: '';
  width: 30%;
}
</style>
